<?php

namespace app\admin\model\facrm\contract;

use app\admin\model\facrm\Operatelog;
use think\Model;
use traits\model\SoftDelete;

class Receivables extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'facrm_contract_receivables';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    protected $append = [
        'account_text'
    ];
	protected static function init()
    {
        $forfun = function (&$row) {
            foreach ($row->data as $k => $v) {
                //数组的字段处理成字符串,主要处理是自定义字段多选的值
                if (!empty($v) && is_array($v)) $row->data[$k] = implode(',', $v);
            }
        };
        self::afterUpdate(
            function ($row) {
                $changed = $row->getChangedData();
                if ($changed && isset($changed['follow_time'])) return;//跟进操作不加日志
                $msg = Operatelog::getTitle() ? "" : "更变收款";
                if ($msg && isset($changed['check_status']) && $changed['check_status']) {
                    //标题存在说明在之前已经赋值过，不再处理
                    $check_status = ['-1' => "未提交", '0' => "待审核-收款", 1 => '审核收款', 2 => '审核通过-收款', 3 => '审核未通过-收款'];
                    $msg = $check_status[$changed['check_status']];
                }

                Operatelog::record(0, $row->contract_id,  $row->id, $msg, json_encode($changed));
            }
        );
        self::afterInsert(function ($row) use ($forfun) {
            //添加操作日志
            Operatelog::record(0, $row->contract_id,  $row->id, Operatelog::getTitle() ? "" : "新增收款", json_encode($row));
        });

        /**
         * 插入前
         */
        self::beforeInsert(function ($row) use ($forfun) {
            $forfun($row);
        });
        /**
         * 更新前
         */
        self::beforeUpdate(function ($row) use ($forfun) {
            $forfun($row);
        });
    }
    /**
     * 获取付款方式
     * @return array
     */
    public function getAccountList()
    {
        $addon_config = get_addon_config('facrm');
        return isset($addon_config['account'])?$addon_config['account']:[];
    }

    /**
     * 获取付款方式名称
     * @param $value
     * @param $data
     * @return array
     */
    public function getAccountTextAttr($value, $data)
    {
        if (!isset($data['account_id'])) return '';
        $lists=$this->getAccountList();

        return isset($lists[$data['account_id']])?$lists[$data['account_id']]:'';
    }
    /**
     * 关联合同
     * @return \think\model\relation\BelongsTo
     */
    public function contract()
    {
        return $this->belongsTo('\app\admin\model\facrm\Contract', 'contract_id', 'id');
    }
    /**
     * 客户
     * @return \think\model\relation\BelongsTo
     */
    public function customer(){
        return $this->belongsTo('\app\admin\model\facrm\Customer', 'customer_id', 'id');
    }

    /**
     * 创建者
     */
    public function createUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'create_user_id');
    }
    /**
     * 负责人
     */
    public function ownerUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'owner_user_id');
    }

    /**
     * 签单人
     * @return \think\model\relation\HasOne
     */
    public function orderAdmin(){
        return $this->hasOne('\app\admin\model\Admin', 'id', 'order_admin_id');
    }
    /**
     * 审批状态
     * @return array
     */
    public function getCheckStatusList(){
        return ['0' => __('待审核'), '1' => __('审核中'),2=>__('审核通过'),3=>__('审核未通过')];
    }

    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['check_status'];
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    /**
     * 根据规则自动生成编码
     * @param $prefix
     * @return int|mixed|string
     */
    public static function autoNo($prefix){
        $replace_data=['Y'=>date('Y'),'m'=>date('m'),'d'=>date('d'),'h'=>date("H"),'i'=>date("i"),'s'=>date("s"),'rand'=>rand(100000,999999)];
        return $prefix?__($prefix, $replace_data):'';
    }
    /**
     * 审批日志
     * @return \think\model\relation\HasMany
     */
    public function flowLog()
    {
        return $this->hasMany('\app\admin\model\facrm\flow\Log', 'types_id', 'id')->where('types', 'receivables');
    }
}